package com.penglecode.netty.server;

import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

@SuppressWarnings({"unchecked", "rawtypes"})
public class NettyServerHandler extends SimpleChannelHandler {

	private static final Logger logger = LoggerFactory.getLogger(NettyServerHandler.class);
	
	private ObjectMethodExecutor objectMethodExecutor;
	
	public NettyServerHandler(ObjectMethodExecutor<?, ?> objectMethodExecutor) {
		super();
		Assert.notNull(objectMethodExecutor, "objectMethodExecutor must be required!");
		this.objectMethodExecutor = objectMethodExecutor;
	}

	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
		logger.error("[server] server internal error!", e.getCause());
		e.getChannel().close();
	}

	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
		logger.debug("[server] received message from client, message = {}", e.getMessage());
		Object response = objectMethodExecutor.executeMethod(e.getMessage());
		e.getChannel().write(response);
	}

	public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
		logger.info("[server] a client channel closed!");
	}

	public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
		logger.info("[server] a client channel connected!");
	}

	public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
		logger.info("[server] a client channel disconnected!");
	}
	
}
